package com.xgc.common.util;

import java.text.DecimalFormat;
public class ChineseNumber {

    private static final String[] NUM_DIGIT = {"", "拾", "佰", "仟"};
    private static final String[] NUM_GRADE = {"", "万", "亿", "万亿", "亿亿"};
    private static final char[] SYMBOL_NUMBER = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'};
    private static final char DOT = '点';

    public static String toChineseNumber(double number) {
        String numberStr = formatInput(number);
        String[] split = numberStr.split("\\.");
        char[] chars = split[0].toCharArray();
        StringBuilder buf = new StringBuilder();
        boolean lastZeroFlag = false; // 上一个字符是否为0
        boolean gradeSkipFlag = true; // true：数级都为0
        for (int i = 0; i < chars.length; i++) {
            int digit = chars.length - i;
            int grade = (digit - 1) / 4; // 数级下标
            int n = char2Number(chars[i]); // 0-9
            int digitFour = (digit - 1) & 3; // 个十百千 四位数位下标
            if (n != 0) { // 不为0的位开始处理
                if (lastZeroFlag) {
                    buf.append(SYMBOL_NUMBER[0]); // 前一位为0，补充前一位
                }
                buf.append(SYMBOL_NUMBER[n]); // 转大写
                buf.append(NUM_DIGIT[digitFour]); // 四位数位
                gradeSkipFlag = false;  // 数级不都为0
            }
            if (digitFour == 0 && !gradeSkipFlag) { // 当前数级结束，如果数级不都为0拼上数级
                buf.append(NUM_GRADE[grade]);
                gradeSkipFlag = true;
            }
            lastZeroFlag = n == 0;
        }
        // 小数
        if (split.length > 1) {
            buf.append(DOT);
            char[] dots = split[1].toCharArray();
            for (char dot : dots) {
                int n = char2Number(dot);
                buf.append(SYMBOL_NUMBER[n]);
            }
        }
        return buf.toString();
    }

    private static String formatInput(double number) {
        DecimalFormat format = new DecimalFormat("0.##########");
        return format.format(number);
    }

    private static int char2Number(char c) {
        return c - '0';
    }

    public static void main(String[] args){
        System.out.println(toChineseNumber(12200.12));
    }
}